实际示例使用 dup 或 dup2

您所在的位置:网站首页 dup 和 dup2 实际示例使用 dup 或 dup2

实际示例使用 dup 或 dup2

2023-03-14 22:35| 来源: 网络整理| 查看: 265

本文介绍了实际示例使用 dup 或 dup2的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我知道什么dup/dup2 可以,但我不知道什么时候会用到.

I know what dup / dup2 does, but I have no idea when it would be used.

有什么实际例子吗?

谢谢.

推荐答案

一个例子是 I/O 重定向.为此,您 fork 一个子进程并关闭 stdin 或 stdout 文件描述符(0 和 1),然后在您选择的另一个文件描述符上执行 dup() ,该文件描述符现在将映射到最低的可用文件描述符,在此案例 0 或 1.

One example use would be I/O redirection. For this you fork a child process and close the stdin or stdout file descriptors (0 and 1) and then you do a dup() on another filedescriptor of your choice which will now be mapped to the lowest available file descriptor, which is in this case 0 or 1.

使用它,您现在可以执行任何可能不知道您的应用程序的子进程,并且每当子进程写入标准输出(或从标准输入读取,无论您配置什么),数据都会写入提供的文件描述符.

Using this you can now exec any child process which is possibly unaware of your application and whenever the child writes on the stdout (or reads from stdin, whatever you configured) the data gets written on the provided filedescriptor instead.

Shell 使用它来实现带有管道的命令,例如/bin/ls | 通过将一个进程的 stdout 连接到另一个进程的 stdin.

Shells use this to implement commands with pipes, e.g. /bin/ls | more by connecting the stdout of one process to the stdin of the other.

这篇关于实际示例使用 dup 或 dup2的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2

实际示例使用 dup 或 dup2 为WP2原创文章,链接:https://www.wp2.cn/other/%e5%ae%9e%e9%99%85%e7%a4%ba%e4%be%8b%e4%bd%bf%e7%94%a8-dup-%e6%88%96-dup2/



【本文地址】


今日新闻


推荐新闻


CopyRight 2018-2019 办公设备维修网 版权所有 豫ICP备15022753号-3